<template>
  <div class="consultation-new">
    <div class="sidebar">
      <div class="sidebar-title">
        <i class="el-icon-user-solid"></i>
        在线医生
      </div>
      <div class="doctor-list">
        <div
          v-for="doctor in doctors"
          :key="doctor.id"
          :class="['doctor-item', doctor.id === (currentDoctor && currentDoctor.id) ? 'active' : '']"
          @click="handleSelectDoctor(doctor)"
        >
          <img :src="doctor.avatar" class="avatar" />
          <div class="info">
            <div class="name">{{ doctor.name }}</div>
            <div class="meta">{{ doctor.specialty }} | {{ doctor.title }}</div>
          </div>
        </div>
      </div>
    </div>
    <div class="chat-area">
      <div class="chat-header" v-if="currentDoctor">
        <div class="header-content">
          <img :src="currentDoctor.avatar" class="avatar" />
          <div class="info">
            <div class="name">{{ currentDoctor.name }}</div>
            <div class="meta">{{ currentDoctor.specialty }} | {{ currentDoctor.title }}</div>
          </div>
        </div>
      </div>
      <div class="chat-header empty" v-else>
        <span>请选择医生进行咨询</span>
      </div>
      <div class="chat-messages" ref="chatMessages">
        <template v-for="(msg, idx) in messages" :key="idx">
          <div
            v-if="msg && msg.sender"
            :class="['msg-bubble', msg.sender === 'admin' ? 'right' : 'left']"
          >
            <img
              v-if="msg.sender === 'user'"
              :src="currentUser && currentUser.avatar || 'https://img.icons8.com/color/48/000000/user-male-circle--v2.png'"
              class="bubble-avatar"
            />
            <div class="bubble-content">
              <div class="bubble-text">{{ msg.content || '[无内容]' }}</div>
              <div class="bubble-time">{{ formatTime(msg.time) }}</div>
            </div>
            <img
              v-if="msg.sender === 'admin'"
              src="https://img.icons8.com/color/48/000000/administrator-male.png"
              class="bubble-avatar"
            />
          </div>
        </template>
      </div>
      <div class="chat-input">
        <el-input
          v-model="newMessage"
          type="textarea"
          :rows="2"
          :placeholder="getInputPlaceholder"
          @keyup.enter.native="handleSendMessage"
          :disabled="!canSendMessage"
        />
        <el-button
          type="primary"
          @click="handleSendMessage"
          :disabled="!canSendMessage || !newMessage.trim()"
        >发送</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapGetters, mapActions } from 'vuex'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

export default {
  name: 'ConsultationNew',
  data() {
    return {
      newMessage: ''
    }
  },
  computed: {
    ...mapState('consultation', [
      'currentUser',
      'doctors',
      'currentDoctor',
      'messages',
      'loading',
      'error'
    ]),
    canSendMessage() {
      return this.currentDoctor && this.currentUser
    },
    getInputPlaceholder() {
      if (!this.currentDoctor) return '请选择医生进行咨询'
      return '请输入您的健康问题'
    }
  },
  watch: {
    error(newError) {
      if (newError) {
        ElMessage.error(newError)
      }
    }
  },
  created() {
    this.initializeConsultation()
  },
  mounted() {
    console.log('messages:', this.messages)
  },
  methods: {
    ...mapActions('consultation', [
      'fetchCurrentUser',
      'fetchDoctors',
      'selectDoctor',
      'fetchMessages',
      'sendMessage'
    ]),
    async initializeConsultation() {
      try {
        await this.fetchCurrentUser()
        await this.fetchDoctors()
      } catch (error) {
        ElMessage.error('初始化咨询页面失败')
      }
    },
    async handleSelectDoctor(doctor) {
      await this.selectDoctor(doctor)
      await this.fetchMessages()
      this.scrollToBottom()
    },
    async handleSendMessage() {
      if (!this.newMessage.trim()) return;

      // 在前端构造完整的消息对象
      const messageToSend = {
        id: `msg${Date.now()}`, // 临时ID，最终ID以后端为准（如果后端生成的话）
        content: this.newMessage.trim(),
        sender: 'user', // 假设当前用户是发送方
        time: new Date().toISOString() // 生成时间戳
      };

      try {
        // 直接将构造好的消息对象传递给 sendMessage action
        await this.sendMessage(messageToSend);

        this.newMessage = '';
        this.scrollToBottom();
      } catch (error) {
        ElMessage.error('发送消息失败');
      }
    },
    scrollToBottom() {
      this.$nextTick(() => {
        const el = this.$refs.chatMessages
        if (el) el.scrollTop = el.scrollHeight
      })
    },
    formatTime(time) {
      if (!time) return ''
      return dayjs(time).format('YYYY-MM-DD HH:mm')
    }
  }
}
</script>

<style scoped>
.consultation-new {
  display: flex;
  min-height: calc(100vh - 80px);
  background: #f7f9fb;
  position: relative;
}

.sidebar {
  width: 300px;
  background: #fff;
  border-right: 1px solid #eee;
  display: flex;
  flex-direction: column;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.05);
}

.sidebar-title {
  font-weight: bold;
  font-size: 20px;
  padding: 24px 20px;
  border-bottom: 1px solid #f0f0f0;
  color: #409eff;
  display: flex;
  align-items: center;
  gap: 8px;
}

.doctor-list {
  flex: 1;
  overflow-y: auto;
}

.doctor-item {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  cursor: pointer;
  border-bottom: 1px solid #f5f5f5;
  transition: all 0.3s ease;
}

.doctor-item.active {
  background: #e6f7ff;
  border-left: 3px solid #409eff;
}

.doctor-item:hover {
  background: #f5f7fa;
}

.avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 14px;
  border: 2px solid #409eff22;
  transition: transform 0.3s ease;
}

.doctor-item:hover .avatar {
  transform: scale(1.05);
}

.info .name {
  font-size: 16px;
  font-weight: 500;
  color: #2c3e50;
}

.info .meta {
  font-size: 13px;
  color: #666;
  margin-top: 4px;
}

.chat-area {
  flex: 1;
  display: block;
  background: #f7f9fb;
}

.chat-header {
  background: #fff;
  border-bottom: 1px solid #eee;
  padding: 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.header-content {
  display: flex;
  align-items: center;
  padding: 18px 28px;
  min-height: 80px;
}

.chat-header.empty {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 16px;
}

.chat-header .avatar {
  width: 54px;
  height: 54px;
  margin-right: 18px;
}

.chat-header .info .name {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}

.chat-header .info .meta {
  font-size: 14px;
  color: #666;
  margin-top: 4px;
}

.chat-messages {
  min-height: 300px;
  padding: 16px 12px 16px 12px;
  background: #f7f9fb;
  overflow-y: auto;
}

.msg-bubble {
  display: flex;
  align-items: flex-end;
  margin-bottom: 24px;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.msg-bubble.left {
  flex-direction: row;
}

.msg-bubble.right {
  flex-direction: row-reverse;
}

.bubble-avatar {
  width: 38px;
  height: 38px;
  border-radius: 50%;
  margin: 0 10px;
  object-fit: cover;
  background: #fff;
  border: 1.5px solid #e0e0e0;
}

.bubble-content {
  max-width: 75%;
  display: flex;
  flex-direction: column;
}

.msg-bubble.left .bubble-content {
  align-items: flex-start;
}

.msg-bubble.right .bubble-content {
  align-items: flex-end;
}

.bubble-text {
  background: #fff;
  border-radius: 12px;
  padding: 12px 18px;
  font-size: 15px;
  color: #2c3e50 !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  line-height: 1.5;
  word-break: break-word;
  min-width: 40px;
  min-height: 20px;
}

.msg-bubble.right .bubble-text {
  background: #409eff;
  color: #fff;
}

.bubble-time {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  padding: 0 4px;
}

.chat-input {
  background: #fff;
  border-top: 1px solid #eee;
  padding: 20px 28px;
  display: flex;
  align-items: flex-end;
  gap: 12px;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
  position: static;
  margin-bottom: 0;
}

.chat-input .el-input {
  flex: 1;
}

.chat-input .el-button {
  min-width: 80px;
  height: 40px;
  border-radius: 20px;
}

@media (max-width: 768px) {
  .consultation-new {
    flex-direction: column;
  }
  
  .sidebar {
    width: 100%;
    height: 300px;
  }
  
  .chat-area {
    height: calc(100vh - 380px);
  }
  
  .bubble-content {
    max-width: 80%;
  }
}
</style> 